//
//  DBUtil.m
//  Shiyun_Newspaper
//
//  Created by zz on 17/6/27.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "DBUtil.h"

#import <FMDB.h>

NSString * const updateKey = @"showupdateData";

@interface DBUtil()

@property (nonatomic, strong) FMDatabase *fmdb;

@property (nonatomic, assign) NSInteger lastSaveTime;

@property (nonatomic, copy) void (^editionAndGradeBlock) (NSError *error,NSDictionary *editionInfo,NSDictionary *gradeInfo);

@end

@implementation DBUtil {
    
    dispatch_group_t group;
    
    NSError *editionAndGradeError;
}

- (BOOL)isShouldUpdate {
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
    NSInteger lastSaveTime = [ud integerForKey:updateKey];

    NSDate *date = [NSDate date];
    NSInteger nowTime = [date timeIntervalSince1970];
    
//    return (nowTime - lastSaveTime) > 60 * 60 * 24;
    return (nowTime - lastSaveTime) > 10;
}

+ (instancetype)shareInstance {
    
    static dispatch_once_t onceToken;
    static DBUtil *dbUtil;
    dispatch_once(&onceToken, ^{
        
        dbUtil = [[self alloc] init];
        
    });
    
    return dbUtil;
}

- (instancetype)init {
    
    if (self = [super init]) {
        
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        NSString *useridStr = [NSString stringWithFormat:@"%@new_cache.db",USERID];
        path = [path stringByAppendingPathComponent:useridStr];
        _fmdb = [FMDatabase databaseWithPath:path];
        
        BOOL canOpen = [_fmdb open];
        
        if (!canOpen) {
            NSLog(@"数据库打开失败");
        }
        
        //建表
        //1.年级
        NSString *gradeClassTableStr = @"create table if not exists t_grade_class_list (id integer primary key autoincrement,info bolb)";
        BOOL b = [_fmdb executeUpdate:gradeClassTableStr];
        if (!b) {
            NSLog(@"年级表初始化失败");
        }
        
        //2.版本
        NSString *editionTableStr = @"create table if not exists t_edition_list (id integer primary key autoincrement,info bolb)";
        b = [_fmdb executeUpdate:editionTableStr];
        if (!b) {
            NSLog(@"版本表初始化失败");
        }
        
        //3.
        
    }
    return self;
}

//更新版本数据
- (void)updateEditionData:(NSDictionary *)dic {
    
    //先删除 在插入
    [self.fmdb executeUpdate:@"delete  from t_edition_list"];
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    BOOL flag = [self.fmdb executeUpdate:@"insert into t_edition_list(info) values (?)",data];
    if (!flag) {
        
        NSLog(@"版本数据写入失败");
    }
}

//更新年级数据
- (void)updateGradeData:(NSDictionary *)dic {
    
    //先删除 在插入
    [self.fmdb executeUpdate:@"delete  from t_grade_class_list"];
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    BOOL flag = [self.fmdb executeUpdate:@"insert into t_grade_class_list (info) values (?)",data];
    
    if (!flag) {
        
        NSLog(@"年级数据写入失败");
    }
    
}

//获取版本数据
- (NSDictionary *)getEditionData {

    FMResultSet *set = [self.fmdb executeQuery:@"select * from t_edition_list"];
    
    while ([set next]) {
        
        NSData *data = [set dataForColumn:@"info"];
        NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        return dic;
    }
    
    return nil;
}

//获取年级数据
- (NSDictionary *)getGradeData {
    
    FMResultSet *set = [self.fmdb executeQuery:@"select * from t_grade_class_list"];
    
    while ([set next]) {
        
        NSData *data = [set dataForColumn:@"info"];
        NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        return dic;
    }
    
    return nil;
}

- (void)getEditionAndGradeData:(void (^)(NSError *, NSDictionary *, NSDictionary *))block {

    static int count = 0;
    
    if ([self isShouldUpdate]) { //大于24小时 需要更新数据
        
        if (count == 3) { //递归三次
            
            NSDictionary *editionDic = [self getEditionData];
            NSDictionary *gradeDic = [self getGradeData];

            if (block) {
                
                block(nil,editionDic,gradeDic);
            }
            
            return;
        }
        
        //先存入block 用于请求完成后回调
        _editionAndGradeBlock = block;
    
        [self requestEditionAndGradeData];
        
        count ++;
        
        
        
    }else { //直接取本地数据库数据
        
        NSDictionary *editionDic = [self getEditionData];
        NSDictionary *gradeDic = [self getGradeData];
        
        if (editionDic == nil || gradeDic == nil) { //如果是空 在去请求
            
            [[NSUserDefaults standardUserDefaults] setDouble:0 forKey:updateKey];
            [self getEditionAndGradeData:block];
            return;
        }
        
        [Utils hideHUD];
        
        if (block) {
            
            block(editionAndGradeError,editionDic,gradeDic);
        }
        
    }
}


/**请求年级和版本数据*/
- (void)requestEditionAndGradeData {
    
//    [Utils showHUD];
    
    group = dispatch_group_create();
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        //执行异步任务1
        [self requestGraderData];
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        // 执行异步任务2
        [self requestVersionData];
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        static int requestTimes = 0;
        
        [Utils hideHUD];
        
        //如果写入成功 才会更新时间
        if (!editionAndGradeError) {
            
            NSDate *date = [NSDate date];
            NSInteger nowDate = [date timeIntervalSince1970];
            
            [[NSUserDefaults standardUserDefaults] setInteger:nowDate forKey:updateKey];
            
            //再次去获取数据
            [self getEditionAndGradeData:_editionAndGradeBlock];
            
        }else { //请求失败  先暂时也更新下时间,防止循环请求
            
            NSDate *date = [NSDate date];
            NSInteger nowDate = [date timeIntervalSince1970];
            
            [[NSUserDefaults standardUserDefaults] setInteger:nowDate forKey:updateKey];
            
            //再次去获取数据
            [self getEditionAndGradeData:_editionAndGradeBlock];
        }
        
        
    });

}

- (void)requestGraderData {
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    
    [param setObject:@"api_classgraders_search" forKey:@"method"];
    
    [Utils getWithparameters:param showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        [self updateGradeData:jsonObject];
        
        dispatch_group_leave(group);
        
    } failure:^(NSInteger recode, NSError *error) {
        editionAndGradeError = error;
        dispatch_group_leave(group);
    }];
    
}

- (void)requestVersionData {
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    [dict setObject:@"api_editiontype_list" forKey:@"method"];
    
    [Utils getWithparameters:dict showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        [self updateEditionData:jsonObject];
        
        dispatch_group_leave(group);
        
    } failure:^(NSInteger recode, NSError *error) {
        editionAndGradeError = error;
        dispatch_group_leave(group);
    }];
}


@end
